package org.piggy.client.rpc.handler;

import com.alibaba.fastjson2.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.piggy.client.rpc.utils.ToolUtil;
import org.piggy.common.async.RequestFuture;
import org.piggy.common.async.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        logger.info("serve response body==============" + msg);
        Response response = JSONObject.parseObject(msg.toString(), Response.class);
        RequestFuture requestFuture = ToolUtil.futures.remove(response.getId());
        requestFuture.receiveResult(response);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ctx.close();
        logger.info("close");
    }
}
